import BaseLayout from '@/layout'
import NProgress from 'nprogress'
import setting from '@/config/setting'
import {useRouterStore} from '@/stores/router'
import {menuToRoutes} from '@/utils/util-menu'
import {useThemeStore} from '@/stores/theme'
import {useUserStore} from '@/stores/user'

NProgress.configure({showSpinner: false})
const userStore = useUserStore()
const routerStore = useRouterStore()
const themeStore = useThemeStore()

export default (router) => {
  router.beforeEach(async (to, from, next) => {
    if (themeStore.theme.nprogress) {
      NProgress.start()
    }
    const {menus, home} = await routerStore.addRouterMenu()
    to.meta.matched = [...to.matched]
    if (menus) {
      router.addRoute({
        path: '/',
        component: BaseLayout,
        redirect: home.path,
        children: menuToRoutes(menus)
      })
    }
    if (to.path === '/404' && to.redirectedFrom !== undefined && userStore.token) {
      next({path: to.redirectedFrom?.fullPath, replace: true})
    } else if (setting.whiteList.includes(to.path) || !setting.tokenValidator || userStore.token) {
      next()
    } else {
      let path = (to.path === '/404' && to.redirectedFrom !== undefined) ? to.redirectedFrom.fullPath : to.path
      next({path: '/login', query: {from: path}})
    }
  })

  router.afterEach(() => {
    if (themeStore.theme.nprogress) {
      NProgress.done()
    }
  })
};

